import React, { Component } from "react";
import { connect } from "react-redux";
import { withRouter } from "react-router-dom";
import { Form, Icon, Input, Button } from "antd";
import Tools from "@/utils/Tools";
import { userAction, permissionsAction, menuAction } from "@/redux/action";
import "./index.scss";

@connect(
	state => state.user,
	{ userAction, permissionsAction, menuAction }
)
@withRouter
@Form.create({ name: "login" })
@setTitle('登录')
export default class Login extends Component {
	state = {
		loading: false
	};

	handleSubmit = e => {
		e.preventDefault();
		this.setState({ loading: true }, () => {
			this.props.form.validateFields(async (err, values) => {
				if (!err) {
					try {
						const result = await window.$api.login(values);
						let menu = await window.$api.getTreeList();
						this.props.menuAction(Tools.processingPath(menu.data))
						this.props.userAction({
							username: result.data.username,
							token: result.data.token
						});
						this.props.permissionsAction(result.data.roles)
						const path = this.props.location.state && this.props.location.state.from;
						this.props.history.push(path || "/");
					} finally {
						this.setState({
							loading: false
						});
					}
				} else {
					this.setState({
						loading: false
					});
				}
			});
		});
	};
	render () {
		const { getFieldDecorator } = this.props.form;

		return (
			<div className="login-container">
				<div className="login-left"></div>
				<div className="login-right">
					<img
						src={require("@/assets/images/logo2.png").default}
						className="logo"
					/>
					<Form onSubmit={this.handleSubmit} className="login-right-container">
						<Form.Item>
							{getFieldDecorator("username", {
								rules: [{ required: true, message: "请输入用户名" }]
							})(
								<Input
									allowClear
									size={"large"}
									maxLength={11}
									prefix={
										<Icon type="user" style={{ color: "rgba(0,0,0,.25)" }} />
									}
									placeholder="请输入用户名"
								/>
							)}
						</Form.Item>
						<Form.Item>
							{getFieldDecorator("password", {
								rules: [{ required: true, message: "请输入密码" }]
							})(
								<Input
									allowClear
									size={"large"}
									maxLength={16}
									prefix={
										<Icon type="lock" style={{ color: "rgba(0,0,0,.25)" }} />
									}
									type="password"
									placeholder="请输入密码"
								/>
							)}
						</Form.Item>
						<Form.Item>
							<Button
								type="primary"
								size={"large"}
								loading={this.state.loading}
								block={true}
								htmlType="submit"
								className="login-form-button"
							>
								{this.state.loading ? "登录中" : "登录"}
							</Button>
						</Form.Item>
					</Form>
				</div>
			</div>
		);
	}
}
